<template>
  <div>
    <el-row >
      <el-card style="overflow: visible">
        <div slot="header">
          <el-button style="float: right; padding: 3px 0" type="text"></el-button>
          <el-tag>挂号</el-tag>
        </div>
        <!-- 添加或修改就诊(门诊)信息(一个病人一个病历号，多次就诊，多次就诊信息)对话框 -->
        <el-row class="app-padding" style="height: 450px">
          <el-col :span="22" :push="2" >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row v-show="false">
                <el-col :span="7">
                  <el-form-item label="患者id" prop="pmsPatient.id">
                    <el-input v-model="form.pmsPatient.id" placeholder="患者id"/>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="看诊医生id" prop="userId">
                    <el-input v-model="form.userId" placeholder="看诊医生id"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="app-padding" :gutter="20">
                <el-col :span="7">
                  <el-form-item label="身份证" prop="pmsPatient.identificationNo">
                    <el-input v-model="form.pmsPatient.identificationNo" @change="queryFlag=true" @blur="queryPatientByIdentificationNo" placeholder="身份证号"/>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="姓名" prop="pmsPatient.name">
                    <el-input v-model="form.pmsPatient.name" placeholder="姓名"/>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="出生日期" prop="pmsPatient.dateOfBirth">
                    <el-date-picker
                      v-model="form.pmsPatient.dateOfBirth"
                      align="right"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="app-padding" :gutter="20">
                <el-col :span="7">
                  <el-form-item label="性别" prop="pmsPatient.gender">
                    <el-select v-model="form.pmsPatient.gender" placeholder="性别">
                      <el-option
                        v-for="item in genderOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="家庭住址" prop="pmsPatient.homeAddress">
                    <el-input v-model="form.pmsPatient.homeAddress" placeholder="家庭住址"/>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="联系方式" prop="pmsPatient.phoneNo">
                    <el-input v-model="form.pmsPatient.phoneNo" placeholder="联系方式"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="app-padding" :gutter="20">
                <el-col :span="7">
                  <el-form-item label="挂号科室" prop="deptId">
                    <tree-select
                      v-model="form.deptId"
                      :options="deptOptions"
                      :disable-branch-nodes="true"
                      :show-count="true"
                      placeholder="请选择科室"
                      @input="$refs.form.validateField('deptId')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="挂号级别" prop="registrationRankId">
                    <el-select v-model="form.registrationRankId" placeholder="挂号级别">
                      <el-option
                        v-for="item in rankOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="挂号日期" prop="attendanceDate">
                    <el-date-picker
                      v-model="form.attendanceDate"
                      align="right"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="app-padding" :gutter="20">
                <el-col :span="7">
                  <el-form-item label="午别" prop="noon">
                    <el-select :disabled="disabledFlag" v-model="form.noon" placeholder="午别 默认下午">
                      <el-option
                        v-for="item in noonOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="看诊医生" prop="skdId">
                    <el-select :disabled="disabledFlag" ref="skdId" clearable v-model="form.skdId" placeholder="看诊医生">
                      <el-option
                        v-for="item in sysUserOptions"
                        :key="item.skdId"
                        :label="item.nickName"
                        :value="item.skdId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="应收金额" prop="price">
                    <el-input v-model="form.price" :disabled="true" placeholder="应收金额"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="app-padding" :gutter="20">
                <el-col :span="7">
                  <el-form-item label="支付方式" prop="catId">
                    <el-select v-model="form.catId" @change="doPay" placeholder="支付方式">
                      <el-option
                        v-for="item in settlementCatOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="病历本" prop="needBook">
                    <el-radio-group v-model="form.needBook">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="2">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>
        <el-row style="text-align: right">
          <el-button type="primary" @click="submitForm">挂号打印&发票</el-button>
        </el-row>
      </el-card>
    </el-row>

    <el-dialog title="支付"
               :visible.sync="dialogPayVisible"
               :close-on-click-modal='false'
               :before-close="handlePayClose"
               @open="openQrCode">
      <div class="qrcode">
        <div id="qrcode"></div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePayClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {handleRegistration,queryRegisterCount} from "@/api/dms/registration";
  import ScrollPane from "../../../layout/components/TagsView/ScrollPane";
  import Icons from "../../components/icons/index";
  import QRCode from 'qrcodejs2'  // 引入qrcode
  import {createPayOrder} from "@/api/pay/pay"
  // 性别
  import {listData} from "@/api/system/dict/data";
  // 挂号级别
  import {listRegistration_rank} from "@/api/sms/registration_rank";
  // 患者
  import {getPatientByIdentificationNo} from "@/api/pms/patient";
  // 结算类别
  import {listCat} from "@/api/bms/cat";
  // 排班
  import {listSysUserBySkd} from "@/api/sms/skd";
  // 科室
  import {treeselect} from "@/api/system/dept";
  // 若依css
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  // 树下拉框
  import TreeSelect from "@riophae/vue-treeselect";
  import {parseTime} from "../../../utils/ruoyi";
  export default {
    name: "addRegistration",
    components: {Icons, ScrollPane, TreeSelect},
    props: ['patientObject', 'invoiceNo'],
    data() {
      return {
        dialogPayVisible: false,
        // select 列表禁用
        disabledFlag: true,
        // 表单参数
        form: {
          pmsPatient: {
            id: null,
            identificationNo: null,
            name: null,
            dateOfBirth: null,
            gender: null,
            homeAddress: null,
            phoneNo: null,
          },
          needBook: "1",
          catId: null,
          attendanceDate:parseTime(new Date(),'{y}-{m}-{d}'),
        },
        // 表单校验
        rules: {
          pmsPatient: {
            identificationNo: [
              {
                required: true, message: "身份证不能为空", trigger: 'blur'
              }, {
                pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
                message: '请输入合法身份证号'
              }
            ],
            name: [{
              required: true, message: "姓名不能为空", trigger: 'blur'
            }],
            dateOfBirth: [{
              required: true, message: "出生日期不能为空", trigger: 'blur'
            }],
            gender: [{
              required: true, message: "请选择性别", trigger: 'change'
            }],
            homeAddress: [{
              required: true, message: "家庭地址不能为空", trigger: 'blur'
            }],
            phoneNo: [{
              required: true, message: "联系方式不能为空", trigger: 'blur'
            }, {
              pattern: /^1[34578]\d{9}$/,
              message: '请输入正确的联系方式(手机号)'
            }]
          },
          deptId: [{
            required: true, message: "请选择挂号科室", trigger: 'input'
          }],
          registrationRankId: [{
            required: true, message: "请选择挂号级别", trigger: 'change'
          }],
          attendanceDate: [{
            required: true, message: "请选择挂号日期", trigger: 'blur'
          }],
          skdId: [{
            required: true, message: "请选择看诊医生", trigger: 'change'
          }],
          catId: [{
            required: true, message: "请选择支付方式", trigger: 'change'
          }],
        },
        // 性别列表
        genderOptions: [],
        // 午别列表
        noonOptions: [{
          value: '0',
          label: '上午'
        }, {
          value: '1',
          label: '下午'
        }],
        // 科室列表
        deptOptions: [],
        // 挂号级别列表
        rankOptions: [],
        // 结算类别列表
        settlementCatOptions: [],
        // 员工(看诊医生)列表
        sysUserOptions: [],
        //是否可以搜索
        queryFlag:true
      };
    },
    created() {
      // 性别列表
      this.getGenderList({dictType: "sys_user_sex"});
      // 科室列表
      this.getDeptList();
      // 挂号级别列表
      this.getRankList();
      // 结算类别
      this.getCatList();
    },
    computed: {
      valueChange() {
        const {attendanceDate, deptId, registrationRankId, noon} = this.form
        return {
          attendanceDate, deptId, registrationRankId, noon
        }
      }
    },
    watch: {
      // 监听看诊医生 变化
      'form.skdId'(val) {
        // 获得医生的ID
        if (val) {
          this.form.userId = this.sysUserOptions.find((sysUser) => (sysUser.skdId === val)).userId;
          return;
        }
        this.form.userId = null;
      },
      // 监听挂号科室、级别、日期是否改变
      valueChange(val) {
        if (val.attendanceDate != null && val.deptId != null && val.registrationRankId != null) {
          val.date = val.attendanceDate;
          // 等于 null 则为 下午
          val.noon = val.noon == null ? "1" : val.noon;
          // 取消禁用
          this.disabledFlag = false;
          // 医生查询
          this.getSysUserList(val);
          // 应收金额 赋值
          this.form.price = this.rankOptions.find((rank) => (rank.id === val.registrationRankId)).price;
        } else {
          this.disabledFlag = true;
        }
      },
      // 患者获取
      patientObject(val) {
        this.form.pmsPatient = val;
        this.form.pmsPatient.gender = val.gender.toString();
      },
      // 发票号获取
      invoiceNo(val) {
        this.form.invoiceNo = val;
      }
    },
    methods: {
      openQrCode() {
        let data = {}
        data.orderId = 1
        data.totalAmount = this.form.price
        data.orderType = 'R'
        createPayOrder(data).then(response => {
          console.log(response)
        })

      },
      qrCode() {
        var _this = this;
        this.$nextTick(function () {
          document.getElementById("qrcode").innerHTML = "";
          let qrcode = new QRCode("qrcode", {
            width: 150,
            height: 150,
            text: "二维码内容",
            colorDark: "#109dff",
            colorLight: "#d9d9d9"
          });
        });
      },
      handlePayClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.dialogPayVisible = false;
          })
          .catch(_ => {});
      },
      doPay() {
        console.log(this.form.catId)
      },
      // 表单重置
      reset() {
        this.form = {
          /*id: null,*/
          createTime: null,
          endAttendance: null,
          status: 0,
          skdId: null,
          deptId: null,
          attendanceDate: parseTime(new Date(),'{y}-{m}-{d}'),
          patientAgeStr: null,
          registrationRankId: null,
          noon: null,
          userId: null,
          price: null,
          catId: null,
          needBook: "1",
          invoiceNo: null,
          pmsPatient: {
            id: null,
            identificationNo: null,
            name: null,
            dateOfBirth: null,
            gender: null,
            homeAddress: null,
            phoneNo: null,
          }
        };
        this.resetForm("form");
      },
      /** 提交按钮 */
      submitForm() {
        if (!this.form.invoiceNo) {
          this.$emit('notify', '发票号不能为空');
          return;
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.getRegisterCount().then(res=>{
               if(!res){
                 handleRegistration(this.form).then(response => {
                   if (response.code === 200) {
                     this.msgSuccess("挂号成功");
                     console.log(response)
                     this.form.orderId = response.data.id
                     // 微信支付
                     if(this.form.catId == 6) {
                       this.msgInfo('微信支付')
                       this.dialogPayVisible = true
                     } else if(this.form.catId == 5) {
                       this.msgInfo('支付宝支付')
                       this.dialogPayVisible = true
                     }
                     this.reset();  // 表单刷新
                     this.$emit('addSuccessBack')
                   }
                 });
               }
            });
          }
        });
      },
      /**性别格式转换*/
      genderFormat(row, column, cellValue) {
        if (cellValue === 0) {
          return "男"
        } else if (cellValue === 1) {
          return "女"
        }
      },
      /** 性别列表获取 */
      getGenderList(params) {
        listData(params).then(response => {
          this.genderOptions = response.rows;
        });
      },
      /** 科室列表获取 */
      getDeptList() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /**挂号级别列表获取 */
      getRankList() {
        listRegistration_rank().then(response => {
          this.rankOptions = response.rows;
        });
      },
      /** 结算类别列表获取 */
      getCatList() {
        listCat().then(response => {
          this.settlementCatOptions = response.rows;
        });
      },
      /** 看诊医生*/
      getSysUserList(params) {
        this.$set(this.form, 'skdId', '');
        this.sysUserOptions = [];
        listSysUserBySkd(params).then(response => {
          this.sysUserOptions = response.rows;
        });
      },
      /** 根据身份证判断用户存在 */
      queryPatientByIdentificationNo(){
        let regExp=/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
       if(!this.form.pmsPatient.identificationNo || !regExp.test(this.form.pmsPatient.identificationNo) || !this.queryFlag){
         return;
       }
        getPatientByIdentificationNo(this.form.pmsPatient.identificationNo).then(response => {
          this.queryFlag=false;
          if (response.data) {
            this.form.pmsPatient = response.data;
            this.form.pmsPatient.gender = response.data.gender.toString();
            this.msgSuccess("用户已存在,已进行读卡");
          }
        })
      },
      /** 查询患者当天在同一个医生下的挂号次数*/
      getRegisterCount(){
        let params = {'userId':this.form.userId,'patientId':this.form.pmsPatient.id,'date':this.form.attendanceDate};
        return  new Promise((resolve,reject)=>{
          queryRegisterCount(params).then(response => {
            if(response.data>0){
              this.$emit('notify', '同一患者只能挂同一个医生同一天的一次号');
            }
            resolve(response.data>0);
          });
        });
      }
    }
  };
</script>

<style scoped>
  .app-padding {
    padding: 5px;
  }

</style>
